define(['app'], function(app) {
    app.controller('fileHistory', function($scope, $http, _dialog, _context, $uibModalInstance, toastr) {
        var self = this;
        self.file = '';
        self.commits = [];
        self.ending = true;
        self.selectAll = false;
        self.diffEnabled = false;
        self.revertEnabled = false;

        var step = 2, lastSha = null;
        var selections = [];

        self.init = function() {
            self.file = _context.file;

            $scope.$watch('dvm.commits', function(newValue) {
                selections = _.filter(newValue, function(commit) {
                    return commit.checked == true;
                });
                self.diffEnabled = (selections.length == 2);
                self.revertEnabled = (selections.length == 1 && newValue.indexOf(selections[0]) > 0);
            }, true);

            loadHistory();
        }

        function loadHistory() {
            $http.post('/note/git/log', {
                file: _context.path,
                step: step,
                sha: lastSha
            }).then(function(response) {
                if (response.status == 200) {
                    step = 5;
                    self.ending = response.data.ending;
                    _.forEach(response.data.commits, function(commit) {
                        lastSha = commit.sha;
                        commit.checked = false;
                        self.commits.push(commit);
                    });
                }
            });
        }

        self.load = function() {
            loadHistory();
        }

        self.select = function() {
            _.forEach(self.commits, function(commit) {
                commit.checked = self.selectAll;
            });
        }

        self.show = function(commit) {
            _dialog.open().showFileInfo({
                path: _context.path,
                sha: commit.sha
            });
        }

        self.diff = function() {
            _dialog.open().showDiffFile({
                file: self.file,
                path: _context.path,
                sha: selections[0].sha,
                shb: selections[1].sha
            });
        }

        self.revert = function() {
            _dialog.confirm('确认信息', '文件的后续版本将被覆盖，您确定要回退吗？').then(function(yes) {
                if (yes) {
                    $http.post('/note/git/revert', {
                        file: _context.path,
                        sha: selections[0].sha
                    }).then(function(response) {
                        if (response.status == 200) {
                            setTimeout(function() {
                                toastr.success('文件版本已回退！');
                                $uibModalInstance.close(true);
                            }, 500);
                        }
                    });
                }
            });
        }

        self.close = function() {
            $uibModalInstance.close();
        }
    });
});
